var express = require('express')
var app = express()
var fs = require('fs')
var path = require('path')
var jwt = require('jsonwebtoken')
var { expressjwt } = require('express-jwt')
app.use(express.static('tate'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(expressjwt({
    secret: '1234',
    algorithms: ['HS256']
}).unless({ path: ['/api/login', '/api/register'] }))
// 注册请求
app.post('/api/register', (req, res) => {
    var { hao, pass } = req.body
    var file = path.join(__dirname, './user/user.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var i = arr.findIndex((item) => {
        return item.hao == hao
    })
    if (i == -1) {
        arr.push({ ...req.body })
        fs.writeFileSync(file, JSON.stringify(arr), 'utf8')
        res.send({ code: 200, msg: '注册成功！', arr })
    } else {
        res.send({ code: 400, msg: '用户已存在，注册失败！' })
    }
})
// 登录请求
app.post('/api/login', (req, res) => {
    var { hao, pass } = req.body
    var file = path.join(__dirname, './user/user.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var i = arr.findIndex((item) => {
        return item.hao == hao && item.pass == pass
    })
    if (i == -1) {
        res.send({ code: 400, msg: '登录失败！' })
    } else {
        const token = jwt.sign({ hao }, '1234', { algorithm: 'HS256', expiresIn: 90 })
        res.send({ code: 200, msg: '登录成功！', arr: arr[i], token })
    }
})
// 数据渲染，分页
app.post('/user/ran', (req, res) => {
    var { page, count } = req.body
    var file = path.join(__dirname, './user/wen.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var length=arr.length
    var arr1 = arr.slice((page - 1) * count, page * count)
    
    res.send({ code: 200, msg: '成功获取数据', list: arr1, length })
})
// 模糊查询
app.post('/api/search', (req, res) => {
    var { name } = req.body
    var file = path.join(__dirname, './user/wen.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var length=arr.length
    var arr2 = arr.filter((item) => {
        return item.name.includes(name)
    })
    res.send({ code: 200, msg: '查询成功！', arr2 ,length})
})
// 删除请求
app.post('/api/delete', (req, res) => {
    var { name } = req.body
    var file = path.join(__dirname, './user/wen.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var length=arr.length
    var i = arr.findIndex((item) => {
        return item.name == name
    })
    if (i == -1) {
        res.send({ code: 400, msg: '删除失败！' })
    } else {
        arr.splice(i, 1)
        fs.writeFileSync(file, JSON.stringify(arr), 'utf-8')
        arr1 = arr.slice(0, 5)
        res.send({ code: 200, msg: '删除成功！', list: arr1,length })
    }
})
app.listen(8080, () => {
    console.log('连接成功');
})